<template>
  <div class="wrapper">
    <!-- header部分 -->
    <div class="header1">
      <div class="header1_left">
        <el-icon @click="back"><ArrowLeftBold /></el-icon>
      </div>
      <div class="header1_right">
         <p>商家信息</p>
      </div>
    </div>

<!--    商家信息-->
    <div class="businessInfo  card">
      <div class="head">
        <div class="left">
        <div class="businessName">
          {{ data.business.businessName }}
        </div>
          <div class="tag">
            <div class="tag_one">4.8分 </div>
            <div class="tag_two"> 蜂鸟准时达</div>
            <div class="tag_three"> 约37分</div>
            <div class="tag_four"> 月售300+</div>
          </div>
        </div>
        <div class="right">
         <img :src="data.business.businessImg">
        </div>
     </div>

      <div class="body">
        <div class="up">公告：亲，如您对我们的餐品服务配送有任何问题和建议，恳请先不要给差评，，请第一时间联系我们解决，一定会让满意！打工不易，请收下留情，店长电话：-----10086</div>
        <div class="down">
          <div class="down_left"> 30减1 | 50减2 | 80减3</div>
          <div class="down_left"> 特价商品</div>
          <div class="down_right"> 2个优惠 <el-icon><ArrowDown /></el-icon></div>
        </div>
      </div>
    </div>

    <!-- 食品列表部分 -->
    <ul class="food">
      <li v-for="(item, index) in data.foodList" :key="index">
        <div class="food-left">
          <img :src="item.foodImg">
          <div class="food-left-info">
            <h3>{{ item.foodName }}</h3>
            <p>{{ item.foodExplain }}</p>
            <p>&#165;{{ item.foodPrice }}</p>
          </div>
        </div>
        <div class="food-right">
          <div>
            <el-icon class="fa fa-minus-circle" @click="minus(index)" v-show="item.quantity !== 0" ><RemoveFilled /></el-icon>
          </div>
          <p><span v-show="item.quantity !== 0">{{ item.quantity }}</span></p>
          <div>
            <el-icon  class="fa fa-plus-circle" @click="add(index)"  ><CirclePlusFilled /></el-icon>
          </div>
        </div>
      </li>
    </ul>

    <!-- 购物车部分 -->
    <div class="cart">
      <div class="cart-left">
        <div class="cart-left-icon" :style="data.totalQuantity === 0 ? 'background-color:#505051;' : 'background-color:#3190E8;'">
          <el-icon><ShoppingCart /></el-icon>
          <div class="cart-left-icon-quantity" v-show="data.totalQuantity !== 0">
            {{ data.totalQuantity }}
          </div>
        </div>
        <div class="cart-left-info">
          <p>&#165;{{ data.totalPrice }}</p>
          <p>另需配送费{{ data.business.deliveryPrice }}元</p>
        </div>
      </div>
      <div class="cart-right">
        <!-- 不够起送费 -->
        <div class="cart-right-item" v-show="data.totalSettle < data.business.starPrice" style="background-color: #535356;cursor: default;">
          &#165;{{ data.business.starPrice }}起送
        </div>
        <!-- 达到起送费 -->
        <div class="cart-right-item" @click="toOrder" v-show="data.totalSettle >= data.business.starPrice">
          去结算
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useSessionStorage } from '@vueuse/core';
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import router from "@/router";
import {ArrowLeftBold} from "@element-plus/icons-vue";



const data = reactive({
  business:{},
  foodList:[],
  businessId:1,
  cartList:[],
  totalQuantity:0,
  totalPrice:0,
  totalSettle:0,
  orderTypeId:1,

  user:JSON.parse(localStorage.getItem('user')),
})

const route = useRoute();
data.businessId = route.query.businessId;
data.orderTypeId = route.query.orderTypeId;

// 获取商家信息
const getBusiness= (businessId)=>{
  request.get(`/Business/getBusinessById/${businessId}`).then(res =>{
    if( res.code === 1){
      data.business= res.data
      //在调用
      getfoodList(data.businessId)
    }else {
      ElMessage.error(res.message)

    }
  })

}
//获取食物信息
const getfoodList= (businessId)=>{
  request.get(`/Food/listFoodByBusinessId/${businessId}`).then(res =>{
    if( res.code === 1){
      data.foodList= res.data
      data.foodList.forEach(item => {
        // 给每个食物项添加 quantity 属性，并初始化为 0
        item.quantity = 0;
      });
      listCart();//在加载购物车
    }else {
      ElMessage.error(res.message)

    }
  })

}

onMounted(async () => {
  await getBusiness(data.businessId); // 等待获取商家信息
});

// 列表购物车中的商品
const listCart=()=> {
  request.get('/Cart/listCart', {
        params: {
          userId:data.user.userId,
          businessId:data.businessId
        }
      }
  ).then(res => {
    if(res.code === 1){
      //把购物车信息给cartList
      data.cartList = res.data
      // 遍历所有食品列表,根据购物车改变食物的购买数量
      data.foodList.forEach(foodItem => {
        foodItem.quantity = 0; // 重置数量
        data.cartList.forEach(cartItem => {
          if (cartItem.foodId === foodItem.foodId) {
            foodItem.quantity += cartItem.quantity;
          }
        });
      });

    }else
    {
      ElMessage.error("你还未购买商品")
    }

  }).catch(error => {
    ElMessage.error("请求购物车数据失败");
  });
}


// 添加到购物车
const add=(index)=> {
  // 首先做登录验证
  if ( data.user == null) {
    // 路由跳转到登录页面
    // 这里假设有一个名为 router 的路由实例
    router.push({
      path: '/login'
    });
    return;
  }
  if (data.foodList[index].quantity == 0) {
    //做insert
    savaCart(index);
  } else {
    //做update
   updateCart(index, 1);
  }

}

// 从购物车减去
const  minus=(index)=> {
  // 首先做登录验证
  if (data.user== null) {
    // 路由跳转到登录页面
    // 这里假设有一个名为 router 的路由实例
    router.push({
      path: '/login'
    });
    return;
  }
  if (data.foodList[index].quantity > 1) {
    //做update
    updateCart(index, -1);
  } else {
    //做delete
    removeCart(index);
  }
}

// 增加一条购物
const savaCart =(index)=> {
  const cartItem = {
    userId: data.user.userId,
    businessId: data.businessId,
    foodId: data.foodList[index].foodId,
  }
  request.post('/Cart/saveCart', cartItem).then(response => {
    if (response.code === 1) {
      //此食品数量要更新为1；
      data.foodList[index].quantity = 1;
      // data.foodList.sort(); 似乎有问题
    } else {
      alert('向购物车中添加食品失败！');
    }
  }).catch(error => {
    console.error(error);
  })
}

// 更新购物车中的商品数量
const updateCart=(index, num)=> {
  const cartItem = {
    userId: data.user.userId,
    businessId: data.businessId,
    foodId: data.foodList[index].foodId,
    quantity: data.foodList[index].quantity +num
  }
  request.put('/Cart/updateCart',cartItem).then(response => {
    if (response.code === 1) {
      // 更新食品数量
      data.foodList[index].quantity += num;
    } else {
      alert('向购物车中更新食品失败！');
    }
  }).catch(error => {
    console.error(error);
  });
}

// 从购物车中删除商品
const removeCart=(index)=> {
  request.delete('/Cart/removeCart', {
    params: {
      userId: data.user.userId,
      businessId: data.businessId,
      foodId: data.foodList[index].foodId,
    }
  }).then(response => {
    if (response.code === 1) {
      // 将食品数量设置为0
      data.foodList[index].quantity = 0;
    } else {
      alert('从购物车中删除食品失败！');
    }
  }).catch(error => {
    console.error(error);
  });
}


// 前往订单页面
const toOrder=()=> {
  router.push({
    path: '/order',
    query: {
      businessId: data.businessId,
      orderTypeId: data.orderTypeId
    }
  });
}

// 计算属性
data.totalPrice = computed(() => {
  return data.foodList.reduce((acc, item) => acc + item.foodPrice * item.quantity, 0);
});

data.totalQuantity = computed(() => {
  return data.foodList.reduce((acc, item) => acc + item.quantity, 0);
});

data.totalSettle = computed(() => {
  return data.totalPrice + data.business.deliveryPrice;
});

const back =()=>{
  router.push({
    path: '/businessList',
    query: {
      orderTypeId: data.orderTypeId
    }
  });
}

</script>

<style scoped>
/*总容器 */
.wrapper {
  width: 100%;
  height: 100%;
}

/*header*/
.wrapper .header1 {
  width: 100%;
  height: 12vw;
  background-color: #17BAF9;
  display: flex;
  justify-content: space-around;
  align-items: center;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  /*保证在最上层*/
  z-index: 1000;
}

.wrapper .header1 .header1_left{
  flex: 3;
  margin-left: 4vw;
  margin-top: 1vw;
}
.wrapper .header1 .header1_right{
  flex: 6;
  margin-left: 2vw;
  font-size: 6vw;
}




.wrapper .businessInfo{
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: 15vw;

}
.wrapper .businessInfo .head{
  margin-left: 2vw;
  flex:1;
  display: flex;
  align-items: center;
}
.wrapper .businessInfo .head .left{
  flex: 6;
  display: flex;
  flex-direction: column;
}
.wrapper .businessInfo .head .left .businessName{

  font-size: 5vw;
  font-weight: bold;
}
.wrapper .businessInfo .head .left .tag{
  display: flex;
  align-items: center;

}
.wrapper .businessInfo .head .left .tag .tag_one{
  color: coral;
  font-weight: bold;
}
.wrapper .businessInfo .head .left .tag .tag_two{
  font-size: 3vw;
  color:#00A6EB;
  border: #17BAF9 0.1vw solid;
  border-radius: 2vw;
  margin-left: 2vw;
  margin-right: 2vw;
}

.wrapper .businessInfo .head .left .tag .tag_three{
  color:black;
  margin-right: 2vw;
}
.wrapper .businessInfo .head .left .tag .tag_four{
  color:black;
  margin-right: 4vw;
}
.wrapper .businessInfo .head .right{
flex: 2;
}
.wrapper .businessInfo .head .right img{
  margin-left: 6vw;
  width: 14vw;
  height: 13vw;
  border-radius: 1vw;
}
.wrapper .businessInfo .body{
  flex: 1;
  margin-left: 2vw;
  display: flex;
  flex-direction: column;
}
.wrapper .businessInfo .body .up{
  color: #9F9F9F;
  white-space: nowrap; /* 保持文本在一行显示 */
  overflow: hidden; /* 隐藏溢出的文本 */
  text-overflow: ellipsis; /* 显示省略号 */
  margin-right: 10vw;
}
.wrapper .businessInfo .body .down {
  display: flex;
  align-items: center;
  margin-top: 1vw;
}
.wrapper .businessInfo .body .down .down_left{
  color: red;
  border-radius: 2vw;
  border: 0.2vw lightcoral solid;
  font-size:3vw;
  padding:0.5vw;
  margin-right: 2vw;
}
.wrapper .businessInfo .body .down .down_right{
  color: #9F9F9F;
}


/* 食品列表部分 */
.wrapper .food {
  width: 100%;
  /*使用下外边距避开footer部分*/
  margin-bottom: 14vw;
}
.wrapper .food li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .food li .food-left {
  display: flex;
  align-items: center;
}
.wrapper .food li .food-left img {
  width: 20vw;
  height: 20vw;
}
.wrapper .food li .food-left .food-left-info {
  margin-left: 3vw;
}
.wrapper .food li .food-left .food-left-info h3 {
  font-size: 3.8vw;
  color: #555;
}
.wrapper .food li .food-left .food-left-info p {
  font-size: 3vw;
  color: #888;
  margin-top: 2vw;
}
.wrapper .food li .food-right {
  width: 16vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .food li .food-right .fa-minus-circle {
  font-size: 5.5vw;
  color: #999;
  cursor: pointer;
}
.wrapper .food li .food-right p {
  font-size: 3.6vw;
  color: #333;
}
.wrapper .food li .food-right .fa-plus-circle {
  font-size: 5.5vw;
  color: #0097EF;
  cursor: pointer;
}
/* 购物车部分 */
.wrapper .cart {
  width: 100%;
  height: 14vw;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
}
.wrapper .cart .cart-left {
  flex: 2;
  background-color: #505051;
  display: flex;
}
.wrapper .cart .cart-left .cart-left-icon {
  width: 16vw;
  height: 16vw;
  box-sizing: border-box;
  border: solid 1.6vw #444;
  border-radius: 8vw;
  background-color: #3190E8;
  font-size: 7vw;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -4vw;
  margin-left: 3vw;
  position: relative;
}
.wrapper .cart .cart-left .cart-left-icon-quantity {
  width: 5vw;
  height: 5vw;
  border-radius: 2.5vw;
  background-color: red;
  color: #fff;
  font-size: 3.6vw;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  right: -1.5vw;
  top: -1.5vw;
}
.wrapper .cart .cart-left .cart-left-info p:first-child {
  font-size: 4.5vw;
  color: #fff;
  margin-top: 1vw;
}
.wrapper .cart .cart-left .cart-left-info p:last-child {
  font-size: 2.8vw;
  color: #AAA;
}
.wrapper .cart .cart-right {
  flex: 1;
}
/*达到起送费时的样式*/
.wrapper .cart .cart-right .cart-right-item {
  width: 100%;
  height: 100%;
  background-color: #38CA73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card{
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0,0,0,.12);
  margin: 2vw;
}
</style>